package com._520it.day1._02_ddl;

import static org.junit.Assert.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

public class DDLDemo {

	// 需求：创建一张t_student表
	@Test
	public void test1() throws Exception {
		// 口诀：贾琏欲执事
		/**
		 * 1.加载注册驱动 2.获取连接对象 3.创建/获取语句对象 4.执行sql语句 5.释放资源
		 */
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "admin");
		Statement st = conn.createStatement();// 创建语句对象
		String sql = "CREATE TABLE `t_student` (`id` bigint(20)  AUTO_INCREMENT,`name` varchar(20) ,`age` int(11) ,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
		st.executeUpdate(sql);
		st.close();
		conn.close();// 释放资源
	}

	// 异常处理
	@Test
	public void test2() {
		// 口诀：贾琏欲执事
		/**
		 * 1.加载注册驱动 2.获取连接对象 3.创建/获取语句对象 4.执行sql语句 5.释放资源
		 */
		Connection conn = null;
		Statement st = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo?useUnicode=true&amp;characterEncoding=utf-8", "root", "");
			st = conn.createStatement();// 创建语句对象
			String sql = "CREATE TABLE `t_student` (`id` bigint(20)  AUTO_INCREMENT,`name` varchar(20) ,`age` int(11) ,PRIMARY KEY (`id`));";
			st.executeUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (st != null) {
				try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					if (conn != null) {
						try {
							conn.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}

	}

	@Test
	public void test3() throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root", "");
				Statement st = conn.createStatement();// 创建语句对象
		) {
			String sql = "CREATE TABLE `t_student` (`id` bigint(20)  AUTO_INCREMENT,`name` varchar(20) ,`age` int(11) ,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
			st.executeUpdate(sql);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
